<script setup>
import { Lock, User } from '@element-plus/icons-vue'
import { ref, watch } from 'vue'
import { userLoginService, userRegisterService } from '@/api/user.js'
import { useUserStore } from '@/stores/index.js'
import { useRouter } from 'vue-router'

// 控制显示登录组件还是注册组件
const isLogin = ref(true)
// 表单的大小统一设置为 large 可选："default" | "small" | "large"
const formSize = ref('large')

// 表单数据校验：“用户注册”
// 1. el-form 绑定至 :model
const formModel = ref({
  username: '',
  password: '',
  repassword: '',
})
// 2. el-form 绑定至 :rules
// a 整个表单的校验规则 required: true非空校验  message: ''提示信息   trigger: ''触发时机：blur失焦 change 改变
// b 长度校验：min: 5, max: 10
// c 正则校验：pattern:
// d 自定义校验：validator: (rules, value, callback) => {}
//   rule当前校验规则 value目前的表单值 callback无论成功都要回调：-callback()成功 --callback(new Error('错误信息'))
// 3. 表单元素 比如 input组件 绑定 form 子属性 v-model="formModel.xxx"
// 4. el-form-item 配置生效哪个规则 <el-form-item prop="username">
const rules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 5, max: 10, message: '用户名必须是5-10位的字符', trigger: 'blur' },
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { pattern: /^\S{6,15}$/, message: '密码必须是6-15位的非空字符', trigger: 'blur' },
  ],
  repassword: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { pattern: /^\S{6,15}$/, message: '密码必须是6-15位的非空字符', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        //判断第二次输入的密码是否一致
        if (value !== formModel.value.password) {
          callback(new Error('两次输入的密码不一致'))
        } else {
          callback() //就算成功也要回调
        }
      },
      trigger: 'blur',
    },
  ],
}

//进行表单提交校验 这个form需要ref="form"绑定，在<el-form>中,这样 await form.value.validate()才能进预校验校验表单
const form = ref()
const register = async () => {
  //预校验校验表单
  await form.value.validate()
  // 开始注册请求
  await userRegisterService(formModel.value)
  //这里 ElMessage 设置了自动化插件按需导入， 报错无需关心
  ElMessage.success('注册成功')
  //这里切换了状态, 后续使用watch来监听更改 isLogin 的值更优雅
  isLogin.value = true
}



watch(isLogin, () => {
  formModel.value = {
    username: '',
    password: '',
    repassword: '',
  }
})

const userStore = useUserStore()
const router = useRouter()
//登录逻辑
const login = async () => {
  //预校验校验表单
  await form.value.validate()
  // 开始登录请求
  const res = await userLoginService(formModel.value)
  //这里 ElMessage 设置了自动化插件按需导入， 报错无需关心
  userStore.setToken(res.data.token)
  ElMessage.success('登录成功')
  router.push('/')
}


</script>

<template>
  <el-row class="login-page" justify="space-around">
    <!--左边半屏-->
    <el-col :xs="18" :span="8" class="left" >
      <div><h1>学习：后台管理系统</h1></div>
    </el-col>

    <!--登录组件-->
    <el-col  :xs="18" :span="6"  class="right">
      <el-form  ref="form" :size="formSize" :model="formModel" :rules="rules" v-if="isLogin" >
        <el-form-item><h1>登录</h1></el-form-item>

        <el-form-item prop="username">
          <el-input v-model="formModel.username" :prefix-icon="User" placeholder="请输入用户名"></el-input>
        </el-form-item>

        <el-form-item prop="password">
          <el-input v-model="formModel.password" :prefix-icon="Lock" placeholder="请输入密码"
                    type="password"></el-input>
        </el-form-item>

        <el-form-item>
          <div class="flex">
            <el-checkbox>记住我</el-checkbox>
            <el-link :underline="false" type="primary">忘记密码？</el-link>
          </div>
        </el-form-item>


        <el-form-item>
          <el-button @click="login" type="primary" auto-insert-space class="button">登录</el-button>
        </el-form-item>

        <el-form-item>
          <el-link :underline="false" type="info" @click="isLogin=false">
            注册 →
          </el-link>
        </el-form-item>
      </el-form>

    <!--注册组件-->
      <el-form ref="form" :size="formSize" :model="formModel" :rules="rules" v-else>
        <el-form-item><h1>注册</h1></el-form-item>

        <el-form-item prop="username">
          <el-input v-model="formModel.username" :prefix-icon="User" placeholder="请输入用户名"></el-input>
        </el-form-item>

        <el-form-item prop="password">
          <el-input v-model="formModel.password" type="password" :prefix-icon="Lock"
                    placeholder="请输入密码"></el-input>
        </el-form-item>

        <el-form-item prop="repassword">
          <el-input v-model="formModel.repassword" type="password" :prefix-icon="Lock"
                    placeholder="请再次输入密码"></el-input>
        </el-form-item>

        <el-form-item>
          <el-button @click="register" type="primary" auto-insert-space class="button">注册</el-button>
        </el-form-item>

        <el-form-item>
          <el-link :underline="false" type="info" @click="isLogin=true">
            ← 返回
          </el-link>
        </el-form-item>
      </el-form>
    </el-col>
  </el-row>
</template>

<style lang="scss" scoped>
.login-page {
  height: 100vh;

  .left {
    margin-top: 15vh;
  }

  .right {
    display: flex;
    flex-direction: column;
    justify-content: center;

    .flex {
      width: 100%;
      display: flex;
      justify-content: space-between;
    }

    .button {
      width: 100%;
    }
  }

}


</style>